import 'dart:async';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:huxiaodui/view/pop_pages/privacy_policy_page.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:huxiaodui/background_run/bg_run.dart';
import 'package:huxiaodui/api/api.dart';
import 'package:huxiaodui/store/store.dart';
import 'package:huxiaodui/theme.dart';
import 'package:huxiaodui/utils/global_controller.dart';
import 'package:huxiaodui/utils/aliyun_push.dart';
import 'package:huxiaodui/utils/tools/notification_tool.dart';
import 'package:huxiaodui/view/home.dart';
import 'package:huxiaodui/view/index/map_page/map_controller.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:permission_handler/permission_handler.dart';

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

// 保留你原来的init方法，但改名为initAppLogic
Future<void> initAppLogic() async {
  NotificationTool.notificationsPlugin.cancelAll();
  await Permission.notification.request();
  await Permission.storage.request();
  Timer.periodic(const Duration(milliseconds: 100), (timer) async {
    if (navigatorKey.currentState != null) {
      timer.cancel();
      await Store.init();
      await SystemPush.init();
      await GlobalController().init();

      try {
        await Api.mobileApp.auth();
        Api.mobileApp.getAlarms();
        Api.mobileApp.nowAlarm();
      } catch (e) {
        log(e.toString());
      }

      try {await Api.other.updateApp(); } catch (e) {log(e.toString());}

      MapController().updateMarkers();
      backgroundServiceInit();
    }
  });

}

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => GlobalController()),
        ChangeNotifierProvider(create: (_) => MapController()),
      ],
      child: const MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: '隐私协议',
      navigatorKey: navigatorKey,
      theme: CustomTheme.light,
      darkTheme: CustomTheme.dark,
      themeMode: ThemeMode.system,
      builder: EasyLoading.init(),
      home: const PrivacyGate(),
    );
  }
}

class PrivacyGate extends StatefulWidget {
  const PrivacyGate({super.key});

  @override
  State<PrivacyGate> createState() => _PrivacyGateState();
}

class _PrivacyGateState extends State<PrivacyGate> {
  bool? _accepted;
  bool _isInitializing = false;

  @override
  void initState() {
    super.initState();
    _checkPrivacy();
  }

  Future<void> _checkPrivacy() async {
    final prefs = await SharedPreferences.getInstance();
    final accepted = prefs.getBool('privacyAccepted') ?? false;
    if (accepted) {
      _startInit();
    } else {
      setState(() {
        _accepted = false;
      });
    }
  }

  Future<void> _startInit() async {
    setState(() {
      _isInitializing = true;
    });

    await initAppLogic();

    setState(() {
      _accepted = true;
      _isInitializing = false;
    });
  }

  void _onAgree() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('privacyAccepted', true);
    _startInit();
  }

  @override
  Widget build(BuildContext context) {
    if (_accepted == null || (_accepted == false && _isInitializing)) {
      // 初始化中或检查隐私状态中显示loading
      return const Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }

    if (_accepted == false) {
      // 未同意隐私政策，显示隐私政策页面
      return PrivacyPolicyPage(onAgree: _onAgree);
    }

    // 已同意且初始化完成，进入主应用内容
    return const AppMainContent();
  }
}

// 保留你的主页包装，包含WillPopScope和MultiProvider
class AppMainContent extends StatelessWidget {
  const AppMainContent({super.key});

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          if (scaffoldKey.currentState?.isDrawerOpen ?? false) {
            scaffoldKey.currentState?.closeDrawer();
            return false;
          } else {
            return await showDialog(
              context: scaffoldKey.currentState?.context ?? context,
              builder: (context) => AlertDialog(
                title: const Text('是否退出？'),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.pop(context, false),
                    child: const Text('取消'),
                  ),
                  TextButton(
                    onPressed: () => Navigator.pop(context, true),
                    child: const Text('确定'),
                  ),
                ],
              ),
            ) ??
                false;
          }
        },
        child: const HomePage(),
    );
  }
}
